package auctions;

import jade.core.Agent;

import jade.domain.FIPAAgentManagement.RefuseException;

import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;

import jade.proto.AchieveREResponder;

/** Class that implements the behaviour of a buyer in a dutch multi-unit 
 * auction.
 * Note that this only provides the communication capabilities. The actual
 * process of bidding is handled by the {@link DutchBuyerStrategy} supplied.
 */
public class DutchBuyer extends AchieveREResponder {
    //the strategy
    private transient DutchBuyerStrategy strategy;

    private int budget;
    private int items;
    
    public DutchBuyer(Agent agent, MessageTemplate mt, 
                      DutchBuyerStrategy strategy, int budget, int items) {
        super(agent, mt);
        this.strategy = strategy;
        this.budget = budget;
        this.items = items;
    }
    
    protected ACLMessage handleRequest(ACLMessage request) 
    throws RefuseException {
        //send message with current budget
        ((BuyerAgent)myAgent).sendBuyerInfo(request.getSender(), budget, items);
        ACLMessage reply = request.createReply();
        String content = request.getContent();
        int itemsForSale = SellerAgent.getNumOfItemsFromMessage(content);
        int price = SellerAgent.getPriceFromMessage(content);
        reply.setPerformative(ACLMessage.AGREE);
        if(strategy.checkOffer(itemsForSale, items, price, budget)) {
            return reply;
        } else {
            throw new RefuseException("");
        }
    }
    
    protected ACLMessage prepareResultNotification(ACLMessage request,
                                                 ACLMessage response) {
        ACLMessage reply = request.createReply();
        String content = request.getContent();
        reply.setPerformative(ACLMessage.INFORM);
        int itemsForSale = SellerAgent.getNumOfItemsFromMessage(content);
        int price = SellerAgent.getPriceFromMessage(content);
        int itemsToBuy = strategy.itemsToBuy(itemsForSale, items, price, 
                                             budget);
        items -= itemsToBuy;
        budget -= itemsToBuy * price;
        reply.setContent(itemsToBuy + "");
        return reply;
    }
}
